import { setToken, getToken, removeToken } from '@/utils/auth'
import { getUserInfoById, getUserInfo, login } from '@/api/user'
const state = {
  userInfo: {},
  token: getToken() || ''
}

const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },

  removeToken() {
    state.token = ''
    state.userInfo = {}
    removeToken()
  }

}
const actions = {
  async login(store, data) {
    // 请求接口
    const res = await login(data)
    // 设置token
    store.commit('setToken', res.data.jwt)
  },
  // 登出
  async logout(store) {
    store.commit('removeToken')
  },
  // 获取用户信息
  async getUserInfo(store) {
    const res = await getUserInfo()
    const userInfo = await getUserInfoById(res.data[0].id)
    store.state.userInfo = { ...res, ...userInfo }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
